package thread;
class MyBlockingQueue{
    private String []elem=null;
    private int size;
    private int head;
    private int tail;
    private Object locker=new Object();
    public MyBlockingQueue(int size){
        elem=new String[size];
        this.size=0;
    }
    public void put(String s) throws InterruptedException {
        synchronized (locker){
            while(size>=elem.length){
                locker.wait();
                //进入阻塞状态
            }

            elem[tail]=s;
            size++;
            tail++;
            if(tail>=elem.length){
                tail=0;

            }
            locker.notify();
        }

    }
    public String take() throws InterruptedException {
        String ret;
      synchronized (locker){
          while(size<=0){//有可能被
              locker.wait();
              //进入阻塞状态
          }

           ret=elem[head];
          head++;
          size--;
          if(head>=elem.length){
              head=0;
          }
          locker.notify();
      }
        return ret;
    }
}
public class ThreadDemon24 {
    public static void main(String[] args) {
        MyBlockingQueue queue=new MyBlockingQueue(100);
        Thread t1=new Thread(()->{
            int count=0;
            while(true){

                try {
                    queue.put(""+count);
                    System.out.println("生产商品"+count);
                    count++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });



        Thread t2=new Thread(()->{
            while(true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    String t=queue.take();
                    System.out.println("消费商品"+t);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        t1.start();
        t2.start();
    }



}
